package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.CurrentUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        Employee employee = CurrentUser.getCurrentUser();
        notice.setIssuer(employee);
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        notice.setPubdate(new Date());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo, Long currentId) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        for (Notice notice : notices) {
            System.out.println(notice);
            List<Long> ids = noticeMapper.selectRelation(notice.getId());
            for (Long id : ids) {
                if (id == currentId) {
                    notice.setRead(true);
                }
            }
        }
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void insertRelation(Long noticeId, Long employeeId) {
        List<Long> ids = noticeMapper.selectRelation(noticeId);
        boolean flag = true;
        for (Long id : ids) {
            if (id == employeeId) {
                flag = false;
            }
        }
        if (flag) {
            noticeMapper.insertRelation(noticeId,employeeId);
        }
    }
}
